package org.cometmi.gwt.echo3.server;

import org.apache.log4j.Logger;
import org.cometmi.gwt.echo3.shared.ClientTestProxy;
import org.cometmi.gwt.server.annotation.QueueHandler;
import org.cometmi.gwt.server.events.QueueEvent;
import org.cometmi.gwt.server.events.QueueEventHandler;
import org.cometmi.gwt.shared.MiQueue;
import org.cometmi.gwt.shared.MiTransaction;
import org.cometmi.gwt.shared.events.BindCallback;
import org.cometmi.gwt.shared.exceptions.InvalidArgumentException;
import org.cometmi.gwt.shared.exceptions.NotAllowedQueueException;

@QueueHandler(queueExpression = "org.cometmi.gwt.test.echo3.client")
public class EchoQueueEventHandler implements QueueEventHandler
{
	static protected Logger logger = Logger.getLogger(EchoQueueEventHandler.class);

	@Override
	public void onCreate(QueueEvent event)
	{
		MiQueue source;
		try
		{
			source = event.getSourceQueue();
			logger.info("Created queue: " + source.getExpression());

			source.bind(new BindCallback()
			{
				@Override
				public void onSuccess()
				{}

				@Override
				public void onError(Throwable t)
				{
					logger.error("Demonstration of attempt to connect to a queue in use: ", t);
				}
			});

			MiTransaction t = source.createTransaction();
			try
			{
				ClientTestProxy p = t.proxyToNewObject(ClientTestProxy.class, "costr str");
				p.myMethod1("string 1");
				p.myMethod1("string 2");
				p.myMethod1("string 3");

				t.commit();
			}
			catch (InvalidArgumentException e)
			{}
		}
		catch (NotAllowedQueueException e1)
		{/* I believe it to be not easily possible */}
	}

	@Override
	public void onDispose(QueueEvent event)
	{
		try
		{
			logger.info("Destroyng queue: " + event.getSourceQueue().getExpression());
		}
		catch (NotAllowedQueueException e)
		{/* I believe it to be not easily possible */}
	}

	@Override
	public void onUpdate(QueueEvent event)
	{}
}
